package com.lagou.edu.service.impl;

import com.lagou.edu.AuthCode;
import com.lagou.edu.mapper.AuthCodeMapper;
import com.lagou.edu.service.AuthCodeService;
import com.lagou.edu.service.EmailServiceFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author
 */
@Slf4j
@Service
public class AuthCodeServiceImpl implements AuthCodeService {

    private final Logger log = LoggerFactory.getLogger(AuthCodeServiceImpl.class);
    @Autowired
    private AuthCodeMapper authCodeMapper;

    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;

    @Override
    public Boolean createAuthCode(String email) {
        int random = ThreadLocalRandom.current().nextInt(100000, 999999);
        String randomCode = String.valueOf(random);
        log.info("{} create authCode is {}", email, random);

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(randomCode);
        long currentTimeMillis = System.currentTimeMillis();
        Timestamp timestamp = new Timestamp(currentTimeMillis);
        authCode.setCreatetime(timestamp);
        //获取十分钟以后的时间
        long expireTime = currentTimeMillis + 10 * 60 * 1000;
        Timestamp expireTimestamp = new Timestamp(expireTime);
        authCode.setExpiretime(expireTimestamp);
        authCodeMapper.insertSelective(authCode);
        return emailServiceFeignClient.sendEmail(email, randomCode);
    }

    @Override
    public Integer validate(String email, String code) {
        AuthCode authCode = authCodeMapper.selectAuthCode(email);
        //没有获取过验证码，返回错误
        if(authCode == null){
            return 1;
        }
        long currentTimeMillis = System.currentTimeMillis();
        Timestamp timestamp = new Timestamp(currentTimeMillis);
        //判断最新code的超时时间是不是过期
        if(authCode.getExpiretime().before(timestamp)){
            return 2;
        }
        //不超时，相等返回正确
        if(authCode.getCode().equals(code)){
            return 0;
        }
        return 1;
    }


}
